package com.thrd.taiexhibition.model;

import android.text.TextUtils;

import com.thrd.basicframework.http.OkHttpUtils;
import com.thrd.basicframework.http.callback.FileCallBack;
import com.thrd.basicframework.utils.LogUtil;
import com.thrd.taiexhibition.BaseApplication;
import com.thrd.taiexhibition.callback.MvpCallback;

import java.io.File;

import okhttp3.Call;

/**
 * @author: ${唐杰}
 * @date: 2021/4/10
 */
public class LyricsModel {
   // String path="http://192.168.179.101/padProject-0.0.1-SNAPSHOT/resource/James/music/yyp.lrc";
    private String mCacheString;

    public  LyricsModel(){
        mCacheString = BaseApplication.mContext.getCacheDir().getAbsolutePath()+"/music/lrc";
    }

    private static final String TAG="LyricsModel";
    public void getLyricsData(String path,MvpCallback<File> mvpCallback){
        String pathName=getFileName(path);
        pathName= TextUtils.isEmpty(pathName)?path.hashCode()+".lrc":pathName;
        File file=new File(mCacheString,pathName);
        if(file.exists()){
            mvpCallback.onSuccess(file);
            return;
        }
        OkHttpUtils.get().url(path).tag(TAG)
                .build().execute(new FileCallBack(mCacheString,pathName) {
            @Override
            public void onError(Call call, Exception e, int id) {
                LogUtil.e(TAG,"onError");
                mvpCallback.onFailed(e.getMessage(),id);
            }

            @Override
            public void onResponse(File response, int id) {
                LogUtil.e(TAG,"onResponse"+response.getPath());
                mvpCallback.onSuccess(response);
            }

            @Override
            public File onJson(String json) throws Exception {
                LogUtil.e(TAG,json);
                return null;
            }

            @Override
            public void inProgress(float progress, long total, int id) {
                super.inProgress(progress, total, id);
                mvpCallback.inProgress(progress,total,id);
            }
        });
    }

    private   String getFileName(String pathandname){
        int  start=pathandname.lastIndexOf( "/" );
        int  end=pathandname.lastIndexOf( "." );
        if  (start!=- 1  && end!=- 1 ) {
            return  pathandname.substring(start+ 1 , end);
        }
        else  {
            return  null ;
        }
    }
}
